package com.solocredit.finance.ui.user.impl

import android.content.Context
import com.solocredit.finance.http.IHttpCallback
import com.solocredit.finance.mvp.presenter.MvpPresenter
import com.solocredit.finance.ui.user.view.IMullaLoginView
import com.solocredit.finance.utils.helper.MullaAnalysisHelper
import com.solocredit.finance.utils.helper.MullaCustomConfigsHelper
import com.solocredit.finance.utils.helper.SharedHelper
import com.solocredit.finance.utils.helper.TestAnalysisAddEvent
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/26 16:26
 * @Annotation：用户登录 Presenter 实现
 */
class MullaLoginPresenterImpl(context: Context?) : MvpPresenter<IMullaLoginView>(context) {
    private var loginModel: MullaLoginModelImpl? = null

    //验证码接口返回参数
    var loginParam = ""

    init {
        loginModel = MullaLoginModelImpl()
    }

    /**
     * 登录
     */
    fun loginMullaAction(){
        var loginMobile = ""
        mvpView?.let {
            loginMobile = it.getMullaMobile()
        }
        //发送验证码之前，需要验证手机号是否在 app配置 accList里存在
        val customize = MullaCustomConfigsHelper.getMullaConfigData()
        var accItem: JSONObject? = null
        if (customize != null){
            val accList = customize.optJSONArray("accList")
            if (accList != null && accList.length() > 0){
                for (i in 0..<accList.length()){
                    val obj = accList.optJSONObject(i)
                    if (loginMobile == obj.optString("accM")){
                        accItem = obj
                        break
                    }
                }
            }
        }
        //accList 存在该手机号，直接进入登录成功流程
        if (accItem != null){
            SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_IS_CONFIG_ACCOUNT,true)
            onMullaLoginSuccess(accItem.optString("accUid"),accItem.optString("accTk"))
            return
        }
        SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_IS_CONFIG_ACCOUNT,false)

        loginModel?.loginMullaAction(loginMobile,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")){
                    0 -> {//登录成功
                        val obj = data.optJSONObject("obj")
                        if (obj != null){
                            val userId = obj.optString("userId")
                            val userToken = obj.optString("token")
                            val type = obj.optString("type")

                            //是否是渠道用户
                            val isAdSource = obj.optString("isAdSource")
                            SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_IS_ADSOURCE,"YES" == isAdSource)

                            //登录类型 == 注册，需要打点
                            if (type == "REGISTER"){
                                TestAnalysisAddEvent.addRegisterEvent()
                            }
                            onMullaLoginSuccess(userId,userToken)
                        }
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView?.showMullaToast(msg)
                        mvpView?.showMullaLoginFailure(data)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView?.hideMullaLoading()
            }
        })
    }

    /**
     * 登录成功
     */
    private fun onMullaLoginSuccess(uid: String, token: String){
        mvpView?.let {
            it.hideMullaLoading()
            //保存手机号码，个人中心使用
            SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_MOBILE, it.getMullaMobile())
        }
        //保存用户登录状态为已登录
        SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_LOGIN,true)
        //保存用户id
        SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_USERID,uid)
        //保存用户Token
        SharedHelper.saveMullaSPData(SharedHelper.MULLA_SPKEY.MULLA_TOKEN,token)
        //初始化analysis lib 赋值 用户id 和 token
        MullaAnalysisHelper.initAnalysisLibAtLoginSuccess()
        //进入欢迎页面
        mvpView?.showMullaMainPage()
    }
}